package handlers

import (
	"encoding/json"
	"net/http"
	"werewolf/core"
)

func ChatHandler(w http.ResponseWriter, r *http.Request) {         //    返回给前端聊天的发言顺序
	
	if r.Method != http.MethodGet {
		http.Error(w, "Invalid request method", http.StatusMethodNotAllowed)
		return
	}

	handle, err := core.Connection()
	if err!= nil {
		http.Error(w, "Error connecting to database" + err.Error(), http.StatusInternalServerError)
	}

	tx, err := handle.Begin()
	if err!= nil {
		tx.Rollback()
		http.Error(w, "Error starting transaction" + err.Error(), http.StatusInternalServerError)
	}
	defer tx.Commit()

	RmNo := r.URL.Query().Get("RmNo")

	rows, err := tx.Query("SELECT No FROM player WHERE RmNo = ? and Survival = 1 order by No", RmNo)
	if err!= nil {
		tx.Rollback()
		http.Error(w, "Error querying database" + err.Error(), http.StatusInternalServerError)
	}
	defer rows.Close()

	var users []int
	for rows.Next() {
		var user int
		err := rows.Scan(&user)
		if err!= nil {
			tx.Rollback()
			http.Error(w, "Error scanning row" + err.Error(), http.StatusInternalServerError)
		}
		users = append(users, user)
	}

	_, err = tx.Exec("UPDATE running SET speaking = ? and boomable = 1 WHERE RmNo = ?", users[0], RmNo)
	if err!= nil {
		tx.Rollback()
		http.Error(w, "Error updating running table" + err.Error(), http.StatusInternalServerError)
	}

	json.NewEncoder(w).Encode(users)
}